package com.tanhua.server.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserService;
import com.tanhua.server.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
//        进入到controller中的方法之前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获取token，如果能根据token获取到用户放行true 否则拦截false
        String token = request.getHeader("Authorization");
        User user = userService.getUserByToken(token);
        if(user==null){
            return false;   // false拦截  true放行
        }
        UserHolder.setUser(user);  // 把用户放入到了ThreadLocal中
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//      执行完controller中的方法之后 应该清除ThreadLocal中的内容
        UserHolder.removeUser();
    }
}
